<?php

use Mapper\MemberModel as MemberMapper;
use Mapper\SparringBuysModel as BuyMapper;
use Mapper\SparringBuyDetailModel as BuyDetailMapper;

class PublishController extends \Base\AbstractController {

    public function sparringBuyAction() {
        $request = $this->getRequest();

        if($request->isPost()) {
            $error           = [];
            $buyMapper       = BuyMapper::getInstance();
            $buyDetailMapper = BuyDetailMapper::getInstance();
            $memberMapper    = MemberMapper::getInstance();

            if($_FILES['file']['error'] > 0) {
                return \Response::errmsg('文件上传失败,请重新上传!');
            }

            if(empty($_FILES['file']['tmp_name']) || substr(strrchr($_FILES['file']['name'], '.'), 1) !== 'csv') {
                return \Response::errmsg('文件不能为空或者文件类型错误,请重新上传');
            }

            $handle     = fopen($_FILES['file']['tmp_name'], 'r');
            $result     = \Lib\File::csv($handle); //解析csv
            $len_result = count($result);

            if($len_result == 0) {
                return \Response::errmsg('文件内容不能为空！');
            }

            for($i = 1; $i < $len_result; $i++) { //循环获取各字段值,插入数据库
                $flage     = 0;
                $mobile    = trim($result[$i][0]);
                $gameId    = (int)trim($result[$i][1]);//中文转码
                $price     = trim($result[$i][2]);
                $level     = iconv('gb2312', 'utf-8', trim($result[$i][3]));
                $server    = iconv('gb2312', 'utf-8', $result[$i][4]);
                $start     = strtotime(trim($result[$i][5]));
                $end       = strtotime(trim($result[$i][6]));
                $manifesto = iconv('gb2312', 'utf-8', trim($result[$i][7]));
                $netBar    = iconv('gb2312', 'utf-8', trim($result[$i][8]));

                $memberModel = $memberMapper->findByMobile($mobile);

                if(empty($memberModel)) {
                    $error[] = trim($result[$i][0]) . '该用户不存在！' . '<br>';
                    continue;
                }

                $uid = $memberModel->getId();

                if(empty($uid) || empty($gameId) || empty($price) || empty($start) || empty($end)) {
                    $error[] = trim($result[$i][0]) . '字段不能为空！' . '<br>';
                    continue;
                }

                if($start < time()) {
                    $error[] = trim($result[$i][0]) . '请发布大于当前时间' . '<br>';
                    continue;
                }

                if($end <= $start) {
                    $error[] = trim($result[$i][0]) . '开始时间不能大于结束时间' . '<br>';
                    continue;
                }

                $tomorrow = strtotime(date('Y-m-d',strtotime("+2 day")));

                if($end > $tomorrow) {
                    $error[] = trim($result[$i][0]) . '只能发布今天和明天' . '<br>';
                    continue;
                }

                //重复性判断
                $buyModels = $buyMapper->fetchAll([
                    'uid'           => $uid,
                    'end_time > ?' => $start,
                    'status'        => \Lib\Consts::SPARRING_DETAIL_STATUS_NORMAL,
                ]);

                if(!empty($buyModels)) {
                    foreach($buyModels as $buyModel) {
                        $detailBeginTime = $buyModel->getBegin_time();

                        if($start > $detailBeginTime || $end > $detailBeginTime ) {
                            $flage = 1;
                            break;
                        }
                    }
                }

                if($flage == 1) {
                    $error[] = trim($result[$i][0]) . '当前时间区段中含有已发布信息' . '<br>';
                    continue;
                }

                $buyModel = new \SparringBuysModel();
                $buyModel->setUid($uid);
                $buyModel->setBegin_time($start);
                $buyModel->setEnd_time($end);
                $buyModel->setAdd_time(time());
                $buyModel->setStatus(\Lib\Consts::SPARRING_BUY_STATUS_NORMAL);

                $buyMapper->begin();
                $buyId = $buyMapper->insert($buyModel);

                // 时间区段
                $timeInterval   = $this->getTimeInterval($start, $end);
                $sprDetailModel = new \SparringBuyDetailModel();

                foreach($timeInterval as $value) {
                    if(!empty($netBar)) {
                        $sprDetailModel->setNet_bar($netBar);
                    }

                    $sprDetailModel->setSparring_buy_id($buyId);
                    $sprDetailModel->setBegin_time($value[0]);
                    $sprDetailModel->setEnd_time($value[1]);
                    $sprDetailModel->setGame_id($gameId);
                    $sprDetailModel->setPrice($price);
                    $sprDetailModel->setGame_level($level);
                    $sprDetailModel->setGame_server($server);
                    $sprDetailModel->setManifesto($manifesto);
                    $sprDetailModel->setGender($memberModel->getGender());
                    $sprDetailModel->setStatus(\Lib\Consts::SPARRING_DETAIL_STATUS_NORMAL);
                    $sprDetailModel->setAdd_time(time());

                    try {
                        $lastId = $buyDetailMapper->insert($sprDetailModel);
                    } catch(\Exception $e) {
                        $lastId = 0;
                    }

                    if($lastId <= 0) {
                        $buyMapper->rollback();
                        $error[] = trim($result[$i][0]) . '插入失败！' . '<br>';
                        continue;
                    } else {
                        $error[] = trim($result[$i][0]) . '插入成功！' . '<br>';
                    }
                }

                $buyMapper->commit();

            }

            fclose($handle); //关闭指针

            return \Response::msg($error);
        }
    }


    /**
     * @desc 获取时间区段
     *
     * @param     $beginTime
     * @param     $endTime
     * @param int $interval
     * @return array
     */
    public function getTimeInterval($beginTime, $endTime, $interval = 3600) {
        $timeArr      = [];
        $timeInterval = $endTime - $beginTime;
        $num          = floor($timeInterval / $interval);
        $remainder    = $timeInterval % $interval;

        for($i = 0; $i < $num; $i++) {
            $timeArr[] = [$beginTime + $i * $interval, $beginTime + $interval * ($i + 1)];
        }

        if($remainder !== 0) {
            $timeArr[] = [$beginTime + $i * $interval, $endTime];
        }

        return $timeArr;
    }
}
